<?php
namespace app\shop\controller;

use app\common\controller\Shop;
use app\common\model\Business\Collection;
use app\common\model\Order\Product as OrderProduct;
use app\common\model\Product\Cart;
use app\common\model\Product\Product as ProductProduct;
use app\common\model\Product\Relation;
use app\common\model\Product\Type;
use think\Request;

use Exception;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

class Product extends Shop
{
    protected $model = null;
    public function __construct(Request $request)
    {
        $this->model = new ProductProduct();
        $this->noLogin = ['*','collection','cart'];
        parent::__construct($request);
    }
    public function type()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $typeList = Type::order('weigh','desc')->select();
        return $typeList;
    }
    public function index()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $where = [];
        $params = $this->request->get();
        isset($params['type']) && $params['type']!='0' && ($where['typeid']=$params['type']);
        isset($params['flag']) && $params['flag']!='0' && ($where['flag']=$params['flag']);
        $sort = isset($params['sort']) ?$params['sort']: 'createtime';
        $order = isset($params['order']) ?$params['order']: 'desc';
        $pageSize = isset($params['pageSize']) ?$params['pageSize']: 6;
        $page = isset($params['page']) ?$params['page']: 1;
        isset($params['keywords']) && $params['keywords']!='' && ($where['name'] = ['like'=>'%'.($params['keywords'] ?? '').'%']);
        
        $list = $this->model
                ->where('status','1')
                ->where($where)
                ->order($sort, $order)
                ->paginate($pageSize,$page);
        return $list;
    }
    public function info()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $id = $this->request->get('id');
        $product = $this->model->where('status','1')->where('id',$id)->find();
        if(!$product)$this->error('查无产品');
        $this->success('获取成功',null,$product);
    }
    public function prop()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $id = $this->request->get('id');
        $propList = Relation::where('proid',$id)->select();
        return $propList;
    }
    public function comment()
    {
        if(!$this->request->isGet())$this->error('请求错误');
        $params = $this->request->get();
        $where = ['proid'=>$params['id'],'status'=>'3'];
        $pageSize = $params['pageSize'] ?? 6;
        $page = $params['page'] ?? 1;
        $list = OrderProduct::with(['business'])->where($where)->paginate($pageSize,$page);
        return $list;
    }
    public function collection()
    {
        $id = $this->request->get('id');
        if(!$id)$this->error('参数错误');
        $busid = $this->business['id'];
        if($this->request->isGet())
        {
            $isCollection = boolval(Collection::where(['busid'=>$busid,'collectid'=>$id,'status'=>'product'])->find());
            return $isCollection;
        }else if($this->request->isPut())
        {
            $change = $this->request->post('change');
            $params = [
                'busid'=>$busid,
                'collectid'=>$id,
                'status'=>'product'
            ];
            if($change){
                $result = Collection::create($params);
                $result?$this->success('收藏成功'):$this->error('收藏失败');
            }else{
                $result = Collection::where($params)->delete();
                $result?$this->success('取消成功'):$this->error('取消失败');
            }
        }
    }
    public function cart()
    {
        $busid = $this->business->id;
        if($this->request->isPut())
        {
            if(!$this->request->get('id')){
                $cartidList = $this->request->post()['value'];
                $params = [];
                $cartList = Cart::where('busid',$busid)->select();
                Db::startTrans();
                try{
                    $cartList->each(function($cart)use($cartidList){
                        $cart['status'] = in_array($cart['id'],$cartidList)?'1':'0';
                        $cart->isUpdate(true)->save();
                    });
                    Db::commit();
                } catch (PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('修改成功');
            }
            $proid = (int)$this->request->get('id');
            $cartid = (int)$this->request->get('cartid');
            if($proid){
                $params = [
                    'busid'=>$busid,
                    'proid'=>$proid,
                ];
                if($cartid){
                    $curNum = Cart::where($params)->sum('nums');
                    $params = ['id'=>$cartid];
                    $reqParams = $this->request->post();
                    $cart = Cart::where($params)->find();

                    $sum = $curNum+$reqParams['nums']-$cart['nums'];
                    $stock = $this->model::where('id',$proid)->column('stock')[0];
                    if($sum>$stock){
                        $this->error('库存不足');
                    }

                    $cart['nums'] = $reqParams['nums'];
                    $cart['total'] = $cart['nums']*$cart['price'];
                    $result = $cart->isUpdate(true)->save();
                    $result?$this->success('修改成功'):$this->error('修改失败');
                }
            }else{
                $this->error('参数错误');
            }
            $reqParams = $this->request->post();
            //判断库存
            $sum = Cart::where($params)->sum('nums')+$reqParams['nums'];
            $stock = $this->model::where('id',$proid)->column('stock')[0];
            if($sum>$stock){
                $this->error('库存不足');
            }
            $params['attrs'] = $reqParams['attrs'];
            $cart = Cart::where($params)->find();
            $result = null;
            if($cart){
                $cart['nums'] += $reqParams['nums'];
                $cart['total'] = $cart['nums']*$cart['price'];
                $result = $cart->isUpdate(true)->save();
            }else{
                $params = array_merge($params,$reqParams);
                $params['total'] = $params['nums']*$params['price'];
                $result = Cart::create($params);
            }
            $result?$this->success('添加成功'):$this->error('添加失败');
        }else if($this->request->isGet())
        {
            $where = ['busid'=>$busid];
            $type = $this->request->get('type','','trim');
            if($type=='num'){
                return Cart::where($where)->sum('nums');
            }
            $status = $this->request->get('status');
            if($status)$where['cart.status'] = $status;
            return Cart::with(['product'])->where($where)->select();
        }else if($this->request->isDelete())
        {
            $cartid = $this->request->get('cartid');
            $where = ['id'=>$cartid,'busid'=>$busid];
            $result = Cart::where($where)->delete();
            $result?$this->success('删除成功'):$this->error('删除失败');
        }
    }
    public function ranking()
    {
        $orderProductModel = new OrderProduct();
        $orderProductList = $orderProductModel
            ->field('count(id) as num,proid')
            ->group('proid')
            ->order('num','desc')
            ->limit(10)
            ->select();
        $list = [];
        foreach($orderProductList as $orderProduct)
        {
            $product = $this->model->get($orderProduct['proid']);
            $op = $orderProductModel->where('proid',$orderProduct['proid'])->order('rate','desc')->find();
            $product['num'] = $orderProduct['num'];
            $product['comment'] = $op['comment'];
            $list[] = $product;
        }
        return $list;
    }
}